# -*- coding: utf-8 -*-
import logging
import math
import time
import re
import urllib2
import sys
import json
from google.appengine.api import memcache

from Crypto.Cipher import AES
from base64 import b64decode, b64encode, decodestring
from datetime import datetime, timedelta

def str2date(str):
	return datetime.strptime(str, '%Y-%m-%d %H:%M:%S')

def date2str(date):
	return datetime.strftime(date, '%Y-%m-%d %H:%M:%S')

def replace_timezone(dt, timezone=None):
	if timezone == 'Asia/Seoul':
		return dt + timedelta(hours=9) # +9 : Asia/Seoul UTC Offset
	else:
		return dt - timedelta(hours=9)
	
	logging.fatal('not supported timezone')
	assert None

def midnightInSec():
	seoul_now = replace_timezone(datetime.now(), 'Asia/Seoul')
	tomorrow = seoul_now + timedelta(days=1)
	tomorrow = datetime(tomorrow.year,tomorrow.month,tomorrow.day)
	return (tomorrow-seoul_now).total_seconds()
	
def datetime_to_seconds(dt):
	return int(math.ceil(time.mktime(dt.timetuple()) + dt.microsecond/1000000.0))

def seconds_to_datetime(seconds):
	return datetime.fromtimestamp(time.mktime(time.localtime(seconds)))

def shrink_push_token(token):
	if not token:
		return None
	return re.sub(r'[<> ]', r"", token)

###############################################################################
## AES256 crypto
BLOCK_SIZE = 16
secret_key = '20a2ffaf1eed2ab636a22f1f1b3a343f'
IV = chr(0)*16
PAD = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE) 
UNPAD = lambda s : s[0:-ord(s[-1])]
def aes256_decrypt(encrypted):
	return encrypted
	#cipher = AES.new(secret_key, AES.MODE_CBC, IV )
	#return UNPAD(cipher.decrypt(b64decode(encrypted)))

def aes256_encrypt(plantext):
	return plantext
	#cipher = AES.new(secret_key, AES.MODE_CBC, IV )
	#return b64encode(cipher.encrypt(PAD(plantext))) 

def json_dumps_encrypt(obj):
	return aes256_encrypt(json.dumps(obj))

def aes256_decrypt_csuse(encrypted):
	cipher = AES.new(secret_key, AES.MODE_CBC, IV )
	return UNPAD(cipher.decrypt(b64decode(encrypted)))
	
###############################################################################
## IOS - verifying IAP
liveURL = 'https://buy.itunes.apple.com/verifyReceipt'
sandboxURL = 'https://sandbox.itunes.apple.com/verifyReceipt'

def verifyIOSReceipt(user, receipt, bid, debug=False):
	jsonData = json.dumps(
		{
			"receipt-data": receipt,
			"password": "46397a77f4f9458983813dd4af9967e2"
		}
	)

	try:
		s = urllib2.urlopen(sandboxURL if debug else liveURL, jsonData)
		responseData = s.read()
		s.close()
		responseJSON = json.loads(responseData)
		status = int(responseJSON['status'])
		if status==0:
			dct = responseJSON['receipt']
			if dct['bid'].find(bid)>=0:
				logging.info('IOS Verifying receipt failed(bid)!!  user = %s' % (user.key.id(),))
				return False
		elif status==21007: # 센드박스테스트용
			return verifyIOSReceipt(user, receipt, bid, True)
		else:
			logging.info('IOS Verifying receipt failed(status)!!  user = %s, status = %s' % (user.key.id(), status,))
		return status
	except Exception as e:
		logging.info('IOS Verifying receipt skipped!!  user = %s, error = %s' % (user.key.id(),e,))
		success=True	#skip
	return success

###############################################################################
## PlayStore - verifying IAB
import base64
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

PUBLIC_KEY_BASE64='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1WCElLtnJfgiSh9wWXkX5PL/OouTgdDNK8V6KojGv/kzNZsU5PDivJSWX+LiHNKbZQU7J4cXvNbdWVUhDv5hLP8sknsoywRTXjDslnr2fQ6HGIiW53tjFDspLy8WhK/Q7jqLPhZE5OSUXT6lCx6riHgR0R4b4JJWe8+ptKEYa1pZp5qHDCewuLU9VvzrBd/igKUlprzzD7rWmvIcRcQT7A8vqrYG5I39yqa4oAnjzHZ9JAuvu5DksOTdsCESsK5EyGL1o71T6TqJ8FzNH/NVf85K7SBE9GC4Bdhvnbx7zNJ+itDr5b1HDLE5XtlML4+F3heOFT6WfIo9nVa6WumX9wIDAQAB'
PUBLIC_KEY= RSA.importKey(base64.standard_b64decode(PUBLIC_KEY_BASE64))

def verifyPlayStoreReceipt(user, receipt, signature):
	try:
		signature = base64.standard_b64decode(signature)
		h = SHA.new()
		h.update(receipt)
		verifier = PKCS1_v1_5.new(PUBLIC_KEY)
		success = verifier.verify(h, signature)
		if success!=True:
			logging.info('PlayStore Verifying receipt failed!!  user = %s' % (user.key.id(),))
		else:
			logging.info('PlayStore Verifying receipt success!!  user = %s' % (user.key.id(),))
	except Exception as e:
		logging.info('PlayStore Verifying receipt error!!  user = %s, error = %s' % (user.key.id(), e,))
		success = False
	return success
